package com.seu.algorithms.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 签名验证
 *
 * @author cashbus
 * @date 2018/08/09
 */
public class SignUtils {
    private static final String SECRET = "buscashcashbus";

    public static String genereateTokenId(final String sessionId) {
        return MD5.md5(sessionId, SECRET);
    }

    /**
     * 获取组合签名字符串
     *
     * @param parmas
     * @return
     */
    public static String getFinalString(Map parmas) {
        if (parmas == null) {
            return "";
        }

        TreeMap treeMap = new TreeMap(parmas);
        // 非线程安全，效率高
        StringBuilder sb = new StringBuilder();
        Iterator iterator = treeMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            if (!"signature".equals(key)) {
                sb.append(key).append("=").append(value).append("&");
            }
        }

        if (sb.length() < 1) {
            return "";
        }
        sb = sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    }

    /**
     * SHA-1签名
     *
     * @param val
     * @return
     */
    public static String getShan(String val) {
        String signature = "";
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(val.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
            return signature;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return signature;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

}
